package ne.aishuyuan.video.view;

import lombok.extern.slf4j.Slf4j;
import ne.aishuyuan.video.bean.Media;
import ne.aishuyuan.video.bean.PlayMedia;
import ne.aishuyuan.video.service.LoadResourceService;
import ne.aishuyuan.video.utils.DeviceInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import uk.co.caprica.vlcj.player.base.*;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.fullscreen.adaptive.AdaptiveFullScreenStrategy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;


/**
 * @ClassName: Player
 * @Description: vlcj 本地播放器
 * @Author: clj
 * @Date: 2021/11/2 16:09
 */
@Slf4j
@EnableScheduling
public class PlayerByLocal extends JFrame {

	private JFrame frame;
	private EmbeddedMediaPlayerComponent mediaPlayerComponent;
	private JPanel contentPane;
	private JPanel controlsPane;
	private Media currentMedia;
	//实际播放清单
	private PlayMedia playMedia;
	//固定播放清单
	private PlayMedia fixedPlayMedia;
	//定时播放清单
	private PlayMedia timerPlayMedia;
	//插播播放清单
	private PlayMedia insertPlayMedia;

	//实际播放列表
	private JComboBox<Media> mediaList;
	//固定播放列表
	private JComboBox<Media> fixedMediaList;
	//定时播放列表
	private JComboBox<Media> timerMediaList;
	//插播播放列表
	private JComboBox<Media> insertMediaList;

	private JButton loadListButton,playNowButton, updateInfo;
	private JTextField text1,text2,text3;
//	private static  final String path="E:\\localresource";
	@Value("${}")
	private static  final String path="/software/mp4";

	@Autowired
	private LoadResourceService loadResourceService;
	private int playRule;

    public PlayerByLocal() {
		frame = new JFrame();
        frame.setBounds(500, 500, 600, 400);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                mediaPlayerComponent.release();
                System.exit(0);
            }
        });
        JPanel contentPane = setContentPane();
        addListener();
        frame.setContentPane(contentPane);
		frame.setVisible(true);
		config();
		load();
    }

	/**
	 * 创建内容面板
	 * @param
	 * @return javax.swing.JPanel
	 */
	private JPanel setContentPane() {
		contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
		mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
			@Override
			public void mouseClicked(MouseEvent  e) {
				//鼠标双击
				if (e.getClickCount() == 2) {
					mediaPlayerComponent.mediaPlayer().fullScreen().toggle();
					mediaList.setVisible(false);
					controlsPane.setVisible(false);
				}
			}
			@Override
			public void mouseWheelMoved(MouseWheelEvent e) {
			}
			//键盘事件
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
					mediaPlayerComponent.mediaPlayer().fullScreen().set(false);
					controlsPane.setVisible(true);
					mediaList.setVisible(true);
				}
				if (e.getKeyCode() == KeyEvent.VK_Q ) {
					mediaPlayerComponent.release();
					System.exit(0);
				}
			}
		};
		contentPane.add(mediaPlayerComponent,BorderLayout.CENTER);
		//播放控制面板
		controlsPane = new JPanel();
		loadListButton = new JButton("加载播放列表");
		controlsPane.add(loadListButton);
		playNowButton = new JButton("插播");
		controlsPane.add(playNowButton);
		//调试代码
		updateInfo = new JButton("更新设备信息");
		SystemInfo si = new SystemInfo();
		HardwareAbstractionLayer hal = si.getHardware();
	 	text1 = new JTextField("getSerialNumber="+ DeviceInfoUtil.getSerialNumber());
	 	text2 = new JTextField("HardwareUUID="+ DeviceInfoUtil.getHardwareUUID());
	 	text3 = new JTextField("processorID="+ DeviceInfoUtil.getProcessorID());
		controlsPane.add(updateInfo);
		controlsPane.add(text1);
		controlsPane.add(text2);
		controlsPane.add(text3);
		contentPane.add(controlsPane, BorderLayout.SOUTH);
		mediaPlayerComponent.mediaPlayer().fullScreen().strategy(new AdaptiveFullScreenStrategy(frame));
		mediaList = new JComboBox<>();
		fixedMediaList = new JComboBox<>();
		timerMediaList = new JComboBox<>();
		insertMediaList = new JComboBox<>();
		contentPane.add(mediaList,BorderLayout.NORTH);
		return contentPane;
    }

    /**
     * 事件
     * @param []
     * @return void
     */
    private void addListener() {
		updateInfo.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				SystemInfo si = new SystemInfo();
				HardwareAbstractionLayer hal = si.getHardware();
				text1 = new JTextField("getSerialNumber="+ DeviceInfoUtil.getSerialNumber() );
				text2 = new JTextField("HardwareUUID="+ DeviceInfoUtil.getHardwareUUID());
				text3 = new JTextField("processorID="+ DeviceInfoUtil.getProcessorID());
			}
		});

    	//加载资源
		loadListButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
//				load();
			}
		});

		//插播 -- 调试代码 后续删除
		playNowButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
			}
		});
    	//播放列表切换事件
        mediaList.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				currentMedia=(Media) e.getItem();
				String url = currentMedia.getPath();
					mediaPlayerComponent.mediaPlayer().media().play(url);
			}
        });
        mediaPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(
        		new MediaPlayerEventAdapter() {
        		    @Override
        		    public void playing(MediaPlayer mediaPlayer) {
        		    	SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
							}
        		    	});
        		    }
        		    @Override
        		    public void finished(MediaPlayer mediaPlayer) {
        		    	mediaPlayer.submit(new Runnable() {
							@Override
							public void run() {
								//顺序播放
									int index = mediaList.getSelectedIndex();
									int max = mediaList.getItemCount();
									if(index + 1 == max)
										   mediaList.setSelectedIndex(0);
									else
									{
										mediaList.setSelectedIndex(index + 1);
									}
							}
						});
        		    }
        		    @Override
        		    public void error(MediaPlayer mediaPlayer) {
        		    	SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								JOptionPane.showMessageDialog(
										frame,
										"Failed to play media",
										"播放失败",
						                JOptionPane.ERROR_MESSAGE);
								frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
							}
        		    	});
        		    }
        	    }
        	);
    }


    /**
     * 加载资源
     * @param []
     * @return void
     */
    public void  load() {
    	File file = new File(path);
    	File[] files = file.listFiles();
    	for (int i=0 ;i< files.length;i++) {
    		Media media = new Media(files[i].getPath());
    		mediaList.addItem(media);
		}

	}



	/**
	 * 暂停播放
	 * @param []
	 * @return void
	 */
	public void  pause() {
		mediaPlayerComponent.mediaPlayer().controls().pause();
	}

	/**
	 * 暂停播放
	 * @param []
	 * @return void
	 */
	public void  stop() {
		mediaPlayerComponent.mediaPlayer().controls().stop();
	}

	/**
	 * 暂停播放
	 * @param []
	 * @return void
	 */
	public void  start() {
		mediaPlayerComponent.mediaPlayer().controls().start();
	}

	/**
     * 装饰配置
     */
    private void config() {
		//字幕功能
		Marquee marquee = Marquee.marquee()
				.text("AI书院媒体播放器")
				.size(30)
				.colour(Color.WHITE)
				.timeout(10000)
				.position(MarqueePosition.TOP_LEFT)
				.opacity(0.3f)
				.enable();
		mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
		//logo
		Logo logo = Logo.logo()
				.file("E:\\resource\\vlcj-logo.png")
				.position(LogoPosition.TOP_RIGHT)
				.opacity(0.5f)
				.enable();
		logo.apply(mediaPlayerComponent.mediaPlayer());
	}
	//	@Scheduled(cron = "0/5 * * * * ?")
	//或直接指定时间间隔，例如：5秒
/*	@Scheduled(fixedRate=7200000)
	private void configureTasks() {
		log.info(">>>>>>>>>>>>>>>>>>>>>>>>定时拉取播放列表");
		load();
	}*/
}
